import {ecs} from '../framework/assets/libs/ecs/ECS';
import {CellModelComponent} from "./cellModelComponent";
import {CellEntity} from "./cellEntity";
import {GridSize, CellStatus} from "../cccomponent/enum";
import {tween, Vec3} from 'cc';
import {smc} from "../config/singletonModule";
import {
    AudioClickComponent,
    CellDieComponent,
    CellViewTurnComponent,
    MoveCellComponent,
    SelectCellComponent,
    UpdateCellStatusComponent
} from "./utilsComponent";
import {ECSEntity} from '../framework/assets/libs/ecs/ECSEntity';
import { Animation } from 'cc';

// 更新格子的状态、播放动画、动效
export class CellViewSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    filter(): ecs.IMatcher {
        return ecs.allOf(CellViewTurnComponent);
    }

    entityEnter(entity: ECSEntity): void {
        entity.remove(CellViewTurnComponent);
        const actions = [];
        const cellModel = entity.get(CellModelComponent);
        let action = null;
        let model;
        if (entity.has(SelectCellComponent)) {
            // 是否选中
            model = entity.get(SelectCellComponent);
            if (model.selectToggle) {
                action = this.updateSelect(cellModel, true);
                if(!cellModel.isSelect) {
                    // 第一次选中才加音效
                    entity.add(AudioClickComponent);
                }
                // 当前选中状态
                cellModel.isSelect = true;
            } else {
                action = this.updateSelect(cellModel, false);
                cellModel.isSelect = false;
                // 不再选中
                entity.remove(SelectCellComponent);
            }
            actions.push(action);
        }
        if (entity.has(MoveCellComponent)) {
            // 移动
            model = entity.get(MoveCellComponent);
            action = this.updateMoveTo(cellModel, model);
            actions.push(action);
            entity.remove(MoveCellComponent);
        }
        if (entity.has(UpdateCellStatusComponent)) {
            model = entity.get(UpdateCellStatusComponent);
            action = this.updateStatus(cellModel, model);
            actions.push(action);
            entity.remove(UpdateCellStatusComponent);
        }
        // 最后处理
        if (entity.has(CellDieComponent)) {
            action = this.updateDie(entity as CellEntity);
            actions.push(action);
            entity.remove(CellDieComponent);
        }
        if (actions.length === 1) {
            // 一个 action 使用 sequence 会报错。。。（智障 cocos）
            actions[0].call(() => this.isCheckGrid()).start();
        } else if (actions.length > 1) {
            tween(cellModel.cellNode)
                .sequence(...actions)
                .call(() => this.isCheckGrid())
                .start();
        }
    }

    updateSelect(model: CellModelComponent, isSelected: boolean) {
        return tween(model.cellNode).call(() => {
            const select = model.cellNode.getChildByName('select');
            // 如果选中
            select.active = isSelected;
        });
    }

    updateMoveTo(cellModel: CellModelComponent, model: MoveCellComponent) {
        // 更新 x，y坐标
        cellModel.x = model.x;
        cellModel.y = model.y;
        const pos = cellModel.getPositionByXy();
        if (model.delayTime > 0) {
            return tween(cellModel.cellNode).to(model.playTime, { position: new Vec3(pos.posX, pos.posY, 0), }).delay(model.delayTime);
        }
        return tween(cellModel.cellNode).to(model.playTime, { position: new Vec3(pos.posX, pos.posY, 0), });
    }

    // 删除
    updateDie(entity: CellEntity) {
        return tween(entity.CellModel.cellNode).call(() => {
            entity.destroy();
        }).removeSelf();
    }
    //
    // updateDelay(entity: CellEntity, delayTime, cb?) {
    //     if (cb) {
    //         return tween(entity.cellNode).delay(delayTime).call(cb);
    //     }
    //     return tween(entity.cellNode).delay(delayTime);
    // }
    //
    // 更新状态
    updateStatus(cellModel: CellModelComponent, model: UpdateCellStatusComponent) {
        const node = cellModel.cellNode;
        cellModel.status = model.newStatus;
        const animation = node.getComponent(Animation);
        return tween(node).call(() => {
            switch (cellModel.status) {
                case CellStatus.bird:
                    animation.play('click');
                    break;
                case CellStatus.column:
                    animation.play('column');
                    break;
                case CellStatus.line:
                    animation.play('line');
                    break;
                case CellStatus.wrap:
                    animation.play('wrap');
                    break;
                case CellStatus.common:
                    animation.play('click');
                    if (!cellModel.isSelect) {
                        animation.stop();
                    }
                    break;
            }
        })
    }

    isCheckGrid() {
        const isResolve = smc.grid.GridModel.isResolve();
        if (isResolve) {
            const allCell = ecs.query(ecs.allOf(CellModelComponent)).length;
            if (allCell < GridSize.gridRows * GridSize.gridColumns) {
                // 需要填充 space
                smc.grid.fillGrid();
            } else {
                // 检查 grid
                smc.grid.allowCheckGrid();
            }
        }
    }
}
